package cn.q3c.download.thread;

import java.io.File;
import java.net.URL;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import cn.keyvalue.ccf.common.http.NewRequestUtils;
import cn.keyvalue.ccf.common.object.Hyperlink;

public class DownloadFileThread implements Runnable {

	private static Logger logger = Logger.getLogger(DownloadFileThread.class);
	private static Logger downloadfileslogger = Logger
			.getLogger("downloadfiles");
	// 下载路径
	private Hyperlink hyperlink;
	// 保存位置
	private File localFile;

	private String charset;
	//xiazai fangshi
	private String type;

	public DownloadFileThread(Hyperlink hyperlink, File file, String charset, String type) {
		this.hyperlink = hyperlink;
		this.localFile = file;
		this.charset = charset;
		this.type = type;
	}

	public void run() {

		try {
			
			if( StringUtils.equalsIgnoreCase(type, "xml") )//xml，html
			{
				Document doc = Jsoup.connect(hyperlink.getUrl()).timeout((int)DateUtils.MILLIS_PER_MINUTE).userAgent(NewRequestUtils.getRandomUserAgent()).get();		
				String content = doc.html();
				FileUtils.writeStringToFile(localFile, content);
			}
			else
			{			
				FileUtils.copyURLToFile(new URL(hyperlink.getUrl()), localFile,
						(int) DateUtils.MILLIS_PER_MINUTE,
						(int) DateUtils.MILLIS_PER_MINUTE);
			}
			// 记录对应日志，时间，链接，文件，字符集 ,一小时记录一个文件
			downloadfileslogger.info(hyperlink.getUrl() + ","
					+ hyperlink.getName() + "," + charset + ","
					+ localFile.toString());
		} catch (Exception e) {
			logger.error("文件下载异常，" + hyperlink.getUrl(), e);
		}
	}
}